#-*- coding: utf-8 -*-

from django.template import Context, loader
from hgWeb.hg.models import Repository,RepositoryContext
from hgWeb.hg.models import LanguageList
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from mercurial import hg, ui
import hgWeb.hg.settings as hg_settings
import os
from django.contrib.auth import authenticate
from django.contrib.auth import login as djano_login


def index(request):
    
    lang = LanguageList.objects.get(language="pl_PL")
    
    if request.user.is_authenticated():
        login = True
    else:
        login = False
    
    hg_repos = Repository.objects.all()
    
    repos = []
    for repo in hg_repos :
        try :
            ctx = RepositoryContext(repo,'tip')
            repo.author = ctx.user
            repo.time = ctx.time
            repos.append(repo)
        except :
            pass
    
    try :
        msg = request.GET["msg"]
        messages_list = msg.split("|")
    except :
        messages_list = []

    t = loader.get_template('hg/html/list.html')
    c = Context({
        'lang' : lang,
        'repositories': repos,
        'messages_list' : messages_list,
        'login' : login
    })
    c.update(csrf(request))
    return HttpResponse(t.render(c))
def add(request):
    msg = []
    err = 0
    try :
        repo_path = request.POST["repository_path"]
        repo_name = request.POST["repository_name"]
        
        if not repo_name :
            if not repo_path :
                msg.append("Nie podano sciezki dla repozytorium !")
                err = 1
            if not err :
                repo_name = repo_path
                msg.append("Nazwa repozytorium została ustalona jako " + repo_path)
          
        if not err :
            repo_path = os.path.join(hg_settings.HG_REPOSITORIES_ROOT,repo_path)
    
            try :
                hg.repository(ui.ui(), repo_path, True)
                new_repo = Repository(
                    name=repo_name,
                    description = request.POST["repository_desc"],
                    path = repo_path
                )
                new_repo.save()
            except :
                msg.append("Wystąpił błąd podczas tworzenia repozytorium")
    except :
        msg.append("Przekierowano na strone główna")
        
    new_url = "/hg/"
    msg2 = ""
    if msg :
        for m in msg :
            msg2 = m + "|"
        msg2 = msg2[:-1]
        new_url = new_url + "?msg=" + msg2
    
    return HttpResponseRedirect(new_url)

def login(request):
    msg = []
    err = 0
    try :
        login_name = request.POST["login_name"]
        login_pass = request.POST["login_pass"]
        
        if not login_name :
            msg.append("Nie podano nazwy uzytkownika")
            err = 1
            
        if not err :
            user = authenticate(username=login_name, password=login_pass)
            if user is not None:
                if user.is_active:
                    djano_login(request, user)
                    msg.append("Zalogowano !") 
    except :
        msg.append("Przekierowano na strone główna")
        
    new_url = "/hg/"
    msg2 = ""
    if msg :
        for m in msg :
            msg2 = m + "|"
        msg2 = msg2[:-1]
        new_url = new_url + "?msg=" + msg2
    
    return HttpResponseRedirect(new_url)